package com.zzh.app.plugin.xhttputils;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.google.gson.Gson;
import com.zzh.app.vo.HerbsModel;
import com.zzh.lib.core.utils.HFileUtils;
import com.zzh.lib.core.utils.HIOUtils;
import com.zzh.lib.core.utils.LogUtils;
import com.zzhx.hawk.Hawk;

import org.xutils.http.common.Callback;
import org.xutils.http.common.impl.HDownloadFileProgressCallback;
import org.xutils.http.request.params.RequestParams;
import org.xutils.http.xHttp;

import java.io.File;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import androidx.appcompat.app.AppCompatActivity;


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.btn_db).setOnClickListener(v -> {
            startActivity(new Intent(MainActivity.this, com.zzh.main.MainActivity.class));
        });
        xHttp.getInstance().init(this.getApplication());
        //https://i3.sinaimg.cn/IT/cr/2014/1203/3651803994.png
        String url = "https://www.baidu.com/s?wd=bing%E6%90%9C%E7%B4%A2%E5%B9%BF%E5%91%8A%E5%B1%8F%E8%94%BD&rsv_spt=1&rsv_iqid=0xd21e7aee000da8b6&issp=1&f=8&rsv_bp=1&rsv_idx=2&ie=utf-8&rqlang=cn&tn=baiduhome_pg&rsv_enter=1&rsv_dl=tb&rsv_btype=t&inputT=2440&rsv_t=e2a2vb0Udv4tN7pwafgdovMfy%2Bh4Pk3M214IolQcpbbGPIkSzvT1EP36GEROzhMtoSMn&rsv_sug3=21&rsv_sug1=22&rsv_sug7=100&oq=bing%2520%25E5%25B9%25BF%25E5%2591%258A%25E5%25B1%258F%25E8%2594%25BD&rsv_pq=ada533700033986c&rsv_sug2=0&prefixsug=bing%25E6%2590%259C%25E7%25B4%25A2%25E5%25B9%25BF%25E5%2591%258A%25E5%25B1%258F%25E8%2594%25BD&rsp=2&rsv_sug4=5020";
        try {
            URI uri = new URI(url);
            String scheme = uri.getScheme();
            String host = uri.getHost();
            Log.e("--", "scheme: " + scheme + ", host: " + host + ", port: " + uri.getPort());
            Log.e("--", "path: " + uri.getPath());
            Log.e("--", "rawPath: " + uri.getRawPath());
            Log.e("--", "params: " + uri.getQuery());
            Log.e("--", "Authority: " + uri.getAuthority());
            Log.e("--", "Fragment: " + uri.getFragment());
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

        List<String> list = new ArrayList<>();
        list.add("1");
        list.add("2");
        list.add("3");
        list.add("4");
        LogUtils.e(TextUtils.join(";", list));

    }

    public void redirectHttpUrl(View view) {
        RequestParams map = new RequestParams("http://msunsoft-test.msunhis.com/msun-his-app-yixin-doctor/account/login");

        map.addParameter("userName", "admin");
        map.addParameter("password", "4UfFB94oP9TgQGkU1jcScw==");
        map.addParameter("isDeptGroup", 1);
        map.addParameter("appType", "yx_android_platform_his");
        map.addParameter("apiDomain", "https://msunsoft-test.msunhis.com/");
        map.addParameter("fromUrl", "msunsoft-test.msunhis.com");
        map.setConnectTimeout(5000);

        xHttp.http().get(map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtils.d(result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                LogUtils.e(ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {
                LogUtils.e(cex);
            }

            @Override
            public void onFinished() {
                LogUtils.d("onFinished");
            }
        });
    }

    public void onClickAccessHttpFileVideo(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1000);
                return;
            }
        }

        RequestParams params = new RequestParams(App.VIDEO_URL_1);
        params.setSaveAlbum(true).setSaveFilePath(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/2/3651803994.mp4");

        xHttp.http().get(params, new Callback.ProgressCallback<File>() {
            @Override
            public void onWaiting() {

            }

            @Override
            public void onStarted() {

                LogUtils.e("----------开始下载：");

            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
                LogUtils.e("----------下载中：total: " + total + ", current: " + current);
            }

            @Override
            public void onSuccess(File result) {
                LogUtils.e("----------下载完成 " + result.getAbsolutePath());
                LogUtils.e("----------下载完成 " + result.exists());
                LogUtils.e("----------下载完成 " + Arrays.toString(result.getParentFile().list()));


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                LogUtils.e("----------下载异常 " + ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                LogUtils.e("----------下载结束");
            }
        });
    }

    public void onClickAccessHttpFileVideo33(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            RequestParams params = new RequestParams(App.VIDEO_URL_1);
            String saveFilePath = HFileUtils.getPublicFile(Environment.DIRECTORY_DOWNLOADS) + File.separator + "eeeeeee.mp4";
            LogUtils.e("---------文件路径1: " + saveFilePath);
            params.setSaveFilePath(saveFilePath);
            xHttp.http().get(params, new HDownloadFileProgressCallback() {
                @Override
                public void onSuccess(File result) {
                    LogUtils.e("---------文件路径2: " + result.getAbsolutePath());
                }
            });
        }
    }


    public void onClickAccessHttpFile(View view) {
        String uri = "http://y1.197784.com/androidzxb.apk";

        RequestParams params = new RequestParams(uri);
        String saveFilePath = HFileUtils.getPublicFile(Environment.DIRECTORY_DOWNLOADS) + File.separator + "eeeeeee.mp4";
        params.setSaveFilePath(saveFilePath);
        xHttp.http().get(params, new Callback.PrepareCallback<InputStream, File>() {

            @Override
            public File prepare(InputStream rawData) throws Throwable {

                HIOUtils.safeWriteFile(rawData, System.currentTimeMillis() + ".mp4", Environment.DIRECTORY_DOWNLOADS);

                return new File(saveFilePath);
            }

            @Override
            public void onSuccess(File result) {
                LogUtils.e(result.getAbsolutePath());
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                LogUtils.e("---onError" + ex.getLocalizedMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                Log.d("---", "-----结束");
            }
        });
    }

    public void onClickAccessHttp(View view) {
        //String uri = "http://wxpic.4006188666.com/upimg/parimg/20220513/1652422197949045.mp4";
        String uri = "http://y1.197784.com/androidzxb.apk";

        RequestParams params = new RequestParams(uri);
        String saveFilePath = HFileUtils.getPublicFile(Environment.DIRECTORY_DOWNLOADS) + File.separator + "eeeeeee.mp4";
        params.setSaveFilePath(saveFilePath);
        xHttp.http().get(params, new Callback.PrepareCallback<InputStream, File>() {

            @Override
            public File prepare(InputStream rawData) throws Throwable {

                HIOUtils.safeWriteFile(rawData, System.currentTimeMillis() + ".mp4", Environment.DIRECTORY_DOWNLOADS);

                return new File(saveFilePath);
            }

            @Override
            public void onSuccess(File result) {
                LogUtils.e(result.getAbsolutePath());
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                LogUtils.e("---onError" + ex.getLocalizedMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                Log.d("---", "-----结束");
            }
        });
        /*xHttp.http().get(params, new Callback.ProgressCallback<File>() {
            @Override
            public void onWaiting() {

            }

            @Override
            public void onStarted() {

            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {

            }

            @Override
            public void onSuccess(File result) {
                LogUtils.d(result.getAbsolutePath());
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("---onError", ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Log.d("---onCancelled", cex.getMessage());
            }

            @Override
            public void onFinished() {
                Log.d("---", "-----结束");
            }
        });*/
    }

    public void redirectHttpParams(View view) {

        String uri = "https://www.baidu.com";
        LogUtils.e(uri);
        ParamMap map = new ParamMap(uri);

        map.setAuth(true);
        map.setShowLoadingDialog(true);

        AppRequestParams params = new AppRequestParams(map.getUrl());
        params.setAuth(map.isAuth());
        params.setShowLoadingDialog(map.isShowLoadingDialog());


        params.setBodyContent("ADFASDFASDFASDF");
        LogUtils.e(params.toString());
        xHttp.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                LogUtils.e(result);


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    String json = "{\n" +
            "            \"orderTemplateContentId\": \"7008840662815737088\",\n" +
            "            \"amountPerPackage\": 1,\n" +
            "            \"catagoryId\": \"602\",\n" +
            "            \"amount\": 1308,\n" +
            "            \"takemedDay\": \"1\",\n" +
            "            \"entrustFlag\": \"0\",\n" +
            "            \"patInHosId\": \"6733407049669149701\",\n" +
            "            \"wbCode\": \"XRX(sz)\",\n" +
            "            \"orderProp\": \"1\",\n" +
            "            \"ycCode\": \"YC202309040005\",\n" +
            "            \"sortNo\": \"1\",\n" +
            "            \"concentration\": \"\",\n" +
            "            \"dosageFormId\": \"22\",\n" +
            "            \"usageTypeJson\": \"{\\n  \\\"pairs\\\" : \\\"7\\\",\\n  \\\"usageTypeId\\\" : \\\"1\\\",\\n  \\\"usageTimeName\\\" : \\\"\\\",\\n  \\\"usageTypeName\\\" : \\\"内服\\\",\\n  \\\"usageTimeId\\\" : \\\"\\\",\\n  \\\"usageMealTimeName\\\" : \\\"\\\",\\n  \\\"accessories\\\" : \\\"\\\",\\n  \\\"usageMethodId\\\" : \\\"3\\\",\\n  \\\"usageMealTimeId\\\" : \\\"\\\",\\n  \\\"usageMethodName\\\" : \\\"无\\\",\\n  \\\"confirmSignDocName\\\" : \\\"\\\",\\n  \\\"herbalBasicDay\\\" : \\\"1\\\",\\n  \\\"confirmSignDocId\\\" : \\\"\\\",\\n  \\\"herbalBasicPairs\\\" : \\\"1\\\"\\n}\",\n" +
            "            \"orderName\": \"丝瓜络(sz)\",\n" +
            "            \"producerName\": \"江阴天江\",\n" +
            "            \"antitumorFlag\": \" \",\n" +
            "            \"herbalDayCount\": 1,\n" +
            "            \"orderDocId\": \"\",\n" +
            "            \"exeDeptId\": \"21\",\n" +
            "            \"dualChannel\": \"0\",\n" +
            "            \"orderNo\": 1,\n" +
            "            \"fullCode\": \"SiGuaLuo(sz)\",\n" +
            "            \"narcosisFlag\": \" \",\n" +
            "            \"insertTime\": \"2024-08-15 10:09:05.000\",\n" +
            "            \"continuedFlag\": \"0\",\n" +
            "            \"spiritTwoFlag\": \"0\",\n" +
            "            \"stockQueryId\": \"6008861814900656395\",\n" +
            "            \"dosageFormName\": \"颗粒剂\",\n" +
            "            \"skinTestTypeId\": \"-1\",\n" +
            "            \"usageMealTimeName\": \"\",\n" +
            "            \"decoctionFeeNumber\": \"7\",\n" +
            "            \"exeDeptName\": \"门诊中药房\",\n" +
            "            \"orderId\": \"6008861814900656395\",\n" +
            "            \"spiritOneFlag\": \"0\",\n" +
            "            \"orderCategoryId\": 602,\n" +
            "            \"ycDeptId\": \"21\",\n" +
            "            \"retailPrice\": 0.38250000000000001,\n" +
            "            \"isAmount\": \"\",\n" +
            "            \"doseUnitId\": \"13\",\n" +
            "            \"templateType\": \"0\",\n" +
            "            \"herbalStoreId\": \"21\",\n" +
            "            \"oneselfDrugFlag\": \"0\",\n" +
            "            \"price\": 0.38250000000000001,\n" +
            "            \"orderDeptName\": \"产科\",\n" +
            "            \"prescriptionRuleCode\": \"\",\n" +
            "            \"decoctingTypeName\": \"常规煎\",\n" +
            "            \"herbalBasicDay\": \"1\",\n" +
            "            \"doseUnitName\": \"g\",\n" +
            "            \"spec\": \"100g\\/660\",\n" +
            "            \"quantity\": 140,\n" +
            "            \"intrapartumFlag\": \"0\",\n" +
            "            \"packingId\": \"15\",\n" +
            "            \"decoctingTypeId\": \"1\",\n" +
            "            \"approvedNo\": \"\",\n" +
            "            \"catagoryName\": \"中药颗粒\",\n" +
            "            \"networkingIndication\": \"\",\n" +
            "            \"nationalMedicalInsuranceCode\": \"\",\n" +
            "            \"decoctingMethodName\": \"无\",\n" +
            "            \"usageTimeName\": \"\",\n" +
            "            \"pairs\": \"7\",\n" +
            "            \"takemedFlag\": \"0\",\n" +
            "            \"OrderType\": \"9\",\n" +
            "            \"drugSpecPackingId\": \"6008839018218391816\",\n" +
            "            \"packageUnitName\": \"g\",\n" +
            "            \"producerId\": \"30581946\",\n" +
            "            \"ycType\": \"0\",\n" +
            "            \"ycStockQueryId\": \"6008861814900656395\",\n" +
            "            \"nationalNegotiatedDrugs\": \"0\",\n" +
            "            \"urgentFlag\": \"0\",\n" +
            "            \"packingName\": \"g\",\n" +
            "            \"selfBurdenRatio\": \"\",\n" +
            "            \"herbalStoreName\": \"门诊中药房\",\n" +
            "            \"preciousFlag\": \" \",\n" +
            "            \"dosageUnit\": \"g\",\n" +
            "            \"modelType\": \"\",\n" +
            "            \"orderSource\": \"130\",\n" +
            "            \"poisonFlag\": \" \",\n" +
            "            \"usageTypeName\": \"内服\",\n" +
            "            \"prescription\": \"\",\n" +
            "            \"patId\": \"6733402399408653700\",\n" +
            "            \"ycId\": \"6008839016305789185\",\n" +
            "            \"ycName\": \"丝瓜络(sz)\",\n" +
            "            \"drugId\": \"6008839016305789185\",\n" +
            "            \"chargeClassId\": \"103\",\n" +
            "            \"babyId\": \"-1\",\n" +
            "            \"hospitalId\": \"10085001\",\n" +
            "            \"orderDocName\": \"梁文超\",\n" +
            "            \"usageWater\": \"\",\n" +
            "            \"orderTemplateDictId\": \"7008840624932783361\",\n" +
            "            \"pairsUnit\": \"1\",\n" +
            "            \"quantityUnit\": \"g\",\n" +
            "            \"speed\": \"\",\n" +
            "            \"decoctingMethodId\": \"3\",\n" +
            "            \"usageMethodName\": \"\",\n" +
            "            \"orderMainId\": \"7008839903713821961\",\n" +
            "            \"inputCode\": \"SGL(sz)\",\n" +
            "            \"slowDiseaseDrugFlag\": \"\",\n" +
            "            \"herbalMemo\": \"共3味7剂 1日1剂 无 内服 \",\n" +
            "            \"savingModeFlag\": \" \",\n" +
            "            \"dosage\": 20,\n" +
            "            \"daysCount\": 7,\n" +
            "            \"usageForHerbalId\": \"1\",\n" +
            "            \"prescriptionRuleName\": \"\",\n" +
            "            \"memo\": \"共3味7剂 1日1剂 无 内服 \",\n" +
            "            \"userSysId\": \"6729925448628701700\",\n" +
            "            \"minDoseCount\": 1,\n" +
            "            \"orgId\": \"10085\",\n" +
            "            \"antibioticsFlag\": \" \",\n" +
            "            \"packageUnitId\": \"15\",\n" +
            "            \"highRiskFlag\": \" \",\n" +
            "            \"usageForHerbalName\": \"先煎\",\n" +
            "            \"prescriptionRuleId\": \"\",\n" +
            "            \"herbalBasicPairs\": \"1\",\n" +
            "            \"dosePerUnit\": 1,\n" +
            "            \"orderType\": \"2\",\n" +
            "            \"orderDeptId\": \"87\",\n" +
            "            \"speedUnit\": \"\",\n" +
            "            \"ycDeptName\": \"门诊中药房\"\n" +
            "        }";

    public void clickSaveLongValue(View view) {
        HerbsModel herbsModel = new Gson().fromJson(json, HerbsModel.class);
        Long value = herbsModel.getStockQueryId();
        LogUtils.e("原始值：" + value);
        Hawk.put("cache_long", herbsModel);
        herbsModel = Hawk.get("cache_long");

        LogUtils.e("存储之后的值：" + herbsModel.getStockQueryId());
    }
}